import datetime

from db import Session
from db.bidding import Shop, Menu


def save_manjian_plan(plans):
    nowTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    session = Session()

    for shop_plan in plans:
        shop = session.query(Shop).filter(Shop.shopId == shop_plan.get("shop_id")).first()
        if not shop:
            session.add(
                Shop(
                    shopId = shop_plan.get("shop_id"),
                    shopName = shop_plan.get("shopName"),
                    manjian = shop_plan.get("mj"),
                    phone = shop_plan.get("phone"),
                    address = shop_plan.get("address"),
                    location = shop_plan.get("location"),
                    shippingFee = shop_plan.get("shipping_fee_tip"),
                    minPrice = shop_plan.get("min_price_tip"),
                    newUserReduceFee = shop_plan.get("new_user_reduce_fee"),
                    createTime = nowTime,
                    updateTime = nowTime,
                )
            )
        else:
            shop.manjian = shop_plan.get("mj")
            shop.phone = shop_plan.get("phone")
            shop.shippingFee = shop_plan.get("shipping_fee_tip")
            shop.minPrice = shop_plan.get("min_price_tip")
            shop.newUserReduceFee=shop_plan.get("new_user_reduce_fee")
            shop.updateTime = nowTime

        sql = "delete from menu where shopId = '{}'".format(shop_plan.get("shop_id"))
        session.execute(sql)


        for act_plan in shop_plan.get("actPlan"):
            session.add(
                Menu(
                    shopId = shop_plan.get("shop_id"),
                    shopName = shop_plan.get("shopName"),
                    totalPackingFee = round(act_plan.get("all_packing_price"),1),
                    totalPrice = round(act_plan.get("total_price"),1),
                    outOfPacket = act_plan.get("out_of_pocket"),
                    menu = str(act_plan.get("menu"))[1:-1],
                )
            )
    session.commit()
    session.close()





